package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.domain.Setmeal;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: com.itheima.service.impl
 * @ClassName: SetmealServiceImpl
 * @Author: Solomon
 * @Date: 2020/7/2 19:11
 * @Description:
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    //分页条件查询检查套餐
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealMapper.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //新增套餐
    @Override
    public void add(Integer[] checkGroupIds, Setmeal setmeal) {
        //先新增检查套餐的基本信息
        setmealMapper.add(setmeal);

        //再新增检查套餐和检查组的关联关系
        if (checkGroupIds != null && checkGroupIds.length > 0){
            setSetmealAndCheckGroup(checkGroupIds,setmeal);
        }

        //新增过后，将图片信息添加进redis集合当中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        //新增过后，生成静态页面
        //generalMobilStaticHtml();
    }

    //编辑套餐时根据id查询套餐基本信息回显
    @Override
    public Setmeal findSetmealById(Integer setmealId) {
        return setmealMapper.findSetmealById(setmealId);
    }

    //检查套餐数据回显时，查询相关联的检查组的信息
    @Override
    public List<Integer> findCheckGroupIdsById(Integer setmealId) {
        return setmealMapper.findCheckGroupIdsById(setmealId);
    }

    //根据id删除检查套餐的信息
    @Override
    public void deleteById(Integer setmealId) {
        //先删除中间表的信息
        setmealMapper.deleteCheckGroupBySetmealId(setmealId);
        //再删除套餐的基本信息
        setmealMapper.deleteBySetmealId(setmealId);

        //删除完成后，重新生成静态页面
        //generalMobilStaticHtml();
    }

    //修改检查套餐的基本信息和中间表的关联信息
    @Override
    public void update(Integer[] checkGroupIds, Setmeal setmeal) {
        //先修改检查套餐的基本信息
        setmealMapper.update(setmeal);

        //要修改检查套餐和检查组之间的关系
        //最方便的就是先删除他们的关系，再重新添加
        setmealMapper.deleteCheckGroupBySetmealId(setmeal.getId());

        if (checkGroupIds != null && checkGroupIds.length > 0){
            setSetmealAndCheckGroup(checkGroupIds,setmeal);
        }
    }

    //移动端查询所有检查套餐的数据
    @Override
    public List<Setmeal> queryAllSetmeal() {
        return setmealMapper.queryAllSetmeal();
    }

    //移动端点击检查套餐时，根据id回显数据，包括（基本信息，检查组信息，检查项信息）
    @Override
    public Setmeal querySetmealById(Integer setmealId) {
        return setmealMapper.querySetmealById(setmealId);
    }

    //查询套餐的名称和预约占比
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealMapper.findSetmealCount();
    }


    //设置检查套餐和检查组之间的关联关系 的方法
    public void setSetmealAndCheckGroup(Integer[] checkGroupIds,Setmeal setmeal){
        List<Map<String,Integer>> list = new ArrayList<>();

        Integer setmealId = setmeal.getId();

        for (Integer checkGroupId : checkGroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmealId",setmealId);
            map.put("checkGroupId",checkGroupId);
            list.add(map);
        }
        setmealMapper.setSetmealAndCheckGroup(list);
    }












    //生成静态页面
    public void generalMobilStaticHtml(){
        //获取套餐数据
        List<Setmeal> setmealList = setmealMapper.queryAllSetmeal();
        //生成套餐列表静态页面
        generalStaticSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generalStaticSetmealDetailHtml(setmealList);
    }


    //生成套餐列表页面的静态页面
    public void generalStaticSetmealListHtml(List<Setmeal> setmealList){
        //创建map集合
        Map<String,Object> map = new HashMap();
        //将list存入map
        map.put("setmealList",setmealList);
        //调用生成方法生成套餐列表
        generalHtml("mobile_setmeal.ftl","m_setmal.html",map);
}

    //用与生成套餐详情的静态页面(可能有多个)
    public void generalStaticSetmealDetailHtml(List<Setmeal> setmealList){
        //传入的集合中，只有setmeal的基本数据，所以我们要根据id重新查询包含检查组，检查项的信息
        for (Setmeal setmeal : setmealList) {
            //创建map集合
            Map<String,Object> map = new HashMap<>();
            //存入map  value是重新查询的详细信息
            map.put("setmeal",setmealMapper.querySetmealById(setmeal.getId()));
            generalHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+ setmeal.getId() +".html",map);
        }
    }

    //编写通用的生成静态页面的方法
    public void generalHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            writer = new FileWriter(new File(outPutPath + htmlPageName));
            template.process(map,writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
